package models

import (
	"context"

	"go.mongodb.org/mongo-driver/bson"
)

// DeviceType 设备类型
type DeviceType struct {
	DeviceName              string   `json:"deviceName" bson:"deviceName"`
	DacNames                []string `json:"dacNames" bson:"dacNames"`
	MaxPointsInDynamicGraph int      `json:"maxPointsInDynamicGraph" bson:"maxPointsInDynamicGraph"`
	DetailedPointsCount     int      `json:"detailedPointsCount" bson:"detailedPointsCount"`
	DetailedPointsMoveSteps int      `json:"detailedPointsMoveSteps" bson:"detailedPointsMoveSteps"`
}

// GetDevice 获取某个设备的信息
func GetDevice(deviceName string) (DeviceType, error) {
	device := DeviceType{}
	err := db.Collection("devices").FindOne(context.TODO(), bson.M{
		"deviceName": deviceName,
	}).Decode(&device)
	return device, err
}

// GetDevices 获取所有设备
func GetDevices() ([]*DeviceType, error) {
	cur, err := db.Collection("devices").Find(context.TODO(), bson.D{})
	if err != nil {
		return nil, err
	}

	results := []*DeviceType{}
	for cur.Next(context.TODO()) {
		var device DeviceType
		if err := cur.Decode(&device); err != nil {
			return nil, err
		}
		results = append(results, &device)
	}

	if err := cur.Err(); err != nil {
		return nil, err
	}
	if err := cur.Close(context.TODO()); err != nil {
		return nil, err
	}
	return results, nil
}

// UpdateDevices 更新所有设备信息
func UpdateDevices(devices []*DeviceType) error {
	_, err := db.Collection("devices").DeleteMany(context.TODO(), bson.D{})
	if err != nil {
		return err
	}

	toInsert := make([]interface{}, len(devices))
	for i, device := range devices {
		toInsert[i] = device
	}
	_, err = db.Collection("devices").InsertMany(context.TODO(), toInsert)
	return err
}
